﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using MP3Ganizer.BusinessObject.Services.Configuration;
using MP3Ganizer.BusinessObject.Services.Classification;
using MP3Ganizer.Common.BaseObject;
using MP3Ganizer.Common.Interfaces.MassEditor;
using Microsoft.Practices.Composite.Presentation.Commands;
using MP3Ganizer.Common.Command;
using MP3Ganizer.BusinessObject.DataToPersist;
using Microsoft.Practices.Composite.Events;
using MP3Ganizer.Events.User;

namespace MP3Ganizer.Modules.MassEditor.ViewModels
{
    public class ArtistsEditorViewModel : BaseModuleViewModel, IArtistsEditorViewModel
    {
        private IUnityContainer _unityContainer;
        private IConfigurationService _configurationService;
        private IEnumerable<string> _artists;
        private string _selectedArtist;
        private List<KeyValuePair<string, double>> _matchingArtists;
        private IClassificationService _classificatonService;
        private KeyValuePair<string, double> _artistToReplace;
        private const string REPLACE_FORMAT_TEXT = "Remplacer {0} par {1}";
        private const string UNAVAILABLE_FORMAT_TEXT = "Pas d'éléments sélectionnés";
        private RelayCommand<object> _replaceCommand;
        private IEventAggregator _eventAggregator;

        public string SelectedArtist
        {
            get { return _selectedArtist; }
            set 
            { 
                _selectedArtist = value;
                OnPropertyChanged("SelectedArtist");
                OnPropertyChanged("ReplaceTxt");
                SetMatchingArtists();
            }
        }
        public IEnumerable<string> Artists
        {
            get { return _artists.OrderBy(item => item); }
            set 
            { 
                _artists = value;
                OnPropertyChanged("Artists");
            }
        }
        public KeyValuePair<string, double> ArtistToReplace
        {
            get { return _artistToReplace; }
            set
            {
                _artistToReplace = value;
                OnPropertyChanged("ArtistToReplace");
                OnPropertyChanged("ReplaceTxt");
            }
        }
        public string ReplaceTxt
        {
            get 
            { 
                return !(string.IsNullOrEmpty(_selectedArtist)) && !string.IsNullOrEmpty(_artistToReplace.Key) ? string.Format(REPLACE_FORMAT_TEXT, _artistToReplace.Key, _selectedArtist) : UNAVAILABLE_FORMAT_TEXT; }
            
        } 
        public RelayCommand<object> ReplaceCommand
        {
            get { return _replaceCommand; }
        }
        public IEnumerable<KeyValuePair<string, double>> MatchingArtists
        {
            get { return _matchingArtists; }
            private set
            {
                _matchingArtists = value.ToList();
                OnPropertyChanged("MatchingArtists");
            }
        }
        
        public ArtistsEditorViewModel(IUnityContainer unityContainer)
        {
            _unityContainer = unityContainer;
            _eventAggregator = _unityContainer.Resolve<IEventAggregator>();
            _configurationService = _unityContainer.Resolve<IConfigurationService>();
            _classificatonService = _unityContainer.Resolve<IClassificationService>();
            _matchingArtists = new List<KeyValuePair<string,double>>();
            _replaceCommand = new RelayCommand<object>(ReplaceAction, CanReplace);
        }



        public void Initialize()
        {
            IEnumerable<OverridableData> results;
            if (_configurationService.GetInfos<OverridableData>(InfoType.Artists, out results))
                Artists = results.Select(item => item.Name);
        }

        private void SetMatchingArtists()
        {
            if (string.IsNullOrEmpty(_selectedArtist))
                return;

            _matchingArtists = new List<KeyValuePair<string, double>>();
            foreach (var artist in _artists)
            {
                if (_selectedArtist.Equals(artist))
                    continue;
                double opacity = _classificatonService.GetPercentageOfString(_selectedArtist, artist) / 100;
                if (opacity > 0.3)
                    _matchingArtists.Add(new KeyValuePair<string, double>(artist, opacity));
            }
            MatchingArtists = _matchingArtists.OrderByDescending(item => item.Value);

        }

        private void ReplaceAction(object e)
        {
            string artistToreplace = _artistToReplace.Key;

            _configurationService.SetInfo(InfoType.Artists, _selectedArtist, artistToreplace);
            _artistToReplace = new KeyValuePair<string, double>(null, 0);
            Initialize();
            SetMatchingArtists();
            base.PropertiesChanged(new string[] { "Artists", "SelectedArtist", "MatchingArtists", "ReplaceTxt", "ArtistToReplace" });
            _eventAggregator.GetEvent<MP3Ganizer.Events.User.UserActionEvent>().Publish(new Events.User.UserActionEventArgs(Common.Enums.UserAction.RefreshFileTree));
        }

        private bool CanReplace(object e)
        {
            return !(string.IsNullOrEmpty(_selectedArtist)) && !string.IsNullOrEmpty(_artistToReplace.Key);
        }
    }
}